# coding=utf-8
import urllib2, time, requests, threading
from bs4 import BeautifulSoup

headers = {
	'Host': '1024.stv919.net',
	'Connection': 'keep-alive',
	'Cache-Control': 'max-age=0',
	'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
	#  'X-Requested-With': 'XMLHttpRequest',
	'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36',
	# 'DNT': '1',
	## 'Accept-Encoding': 'gzip, deflate',
	'Accept-Language': 'zh-CN,zh;q=0.8,ja;q=0.6',
	'Referer': 'http://1024.stv919.net/pw/thread.php?fid=14'
}

url = "http://1024.stv919.net/pw/htm_data/14/1707/7007%d.html"

path = "c://WORKSPACE//logs//"


# urls = [url % (x) for x in range(80, 90, 1)]


def run_page(urlitem):
	print urlitem
	conn = requests.session()
	rsp = requests.get(url=urlitem, headers=headers)
	print rsp.status_code
	try:
		html = rsp.content
		h = BeautifulSoup(html, "html.parser")
		items = h.select('.tpc_content img')
		pic_num = len(items)
		index = 0
		for i in items:
			pic = requests.get(i['src'])
			name = str(long(int(round(time.time() * 1000))))
			f = open(path + name + ".jpg", 'wb')
			f.write(pic.content)
			f.close()
			index += 1
			print i['src'] + ' is ok,%d,%s,%s ' % (index, threading.currentThread().name,threading.currentThread().name)
		# urllib.urlretrieve(i['src'], 'C://WORKSPACE//logs//' + str(long(int(round(time.time() * 1000)))) + ".gzip")
	except urllib2.HTTPError, e:
		print e.code, e.reason
	conn.close()
	print '# all is ok %d' % (pic_num)


######################################################
def main():
	print '####################################'
	start = input("input start>>>>")
	end = input("input end>>>>")
	# path = input("path>>>>")
	# print start, end, path
	for u in range(start, end, 1):
		print '>>>>>' + url % (u)
		run_page(url % (u))
		# print type(u)
		t = threading.Thread(None, name='thread %d' % (u), target=run_page, args=(url % (u),))
		##t.setDaemon(True)
		t.start()
	# t.join()
	print 'all is ok'


if __name__ == '__main__':
	main()
